<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :before-is-show="true">
        <template #before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template slot="after">
          <el-button size="small" type="warning" @click="onImport">导入</el-button>
          <el-button size="small" type="danger" @click="onExport">导出</el-button>
          <el-button size="small" type="primary" @click="addEE">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table v-if="!loading" :data="list" border>
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="头像" width="120" align="center">
            <template v-slot="{ row }">
              <img v-imageError="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="qrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column align="center" prop="username" label="姓名" sortable="" />
          <el-table-column align="center" prop="workNumber" label="工号" sortable="" />
          <el-table-column align="center" prop="formOfEmployment" label="聘用形式" sortable="" :formatter="colFormate" />
          <el-table-column align="center" prop="departmentName" label="部门" sortable="" />
          <el-table-column align="center" label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | forMateDate }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="inServiceStatus" label="账户状态" sortable="">
            <template #default="{ row }">
              <el-switch
                :value="row.inServiceStatus === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/details/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="roleBtn(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEE(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            @current-change="onchangPage"
          />
        </el-row>

        <!-- 新增弹层 -->
        <AddEE
          :add-pop-show.sync="addPopShow"
          @freshList="getEmployeeList"
        />
        <!-- 新增弹层 -->

        <!-- 二维码弹出 -->
        <el-dialog title="二维码" :visible.sync="showCodeDialog">
          <el-row type="flex" justify="center">
            <canvas ref="myCanvas" />
          </el-row>
        </el-dialog>
        <!-- 二维码弹出 -->

        <!-- 角色操作弹出 -->
        <AsightROle ref="roleDialog" :show-role-dialog.sync="roleDialogShow" :user-id="userId" />
        <!-- 角色操作弹出 -->
      </el-card>
    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import AddEE from './components/Add-EE.vue'
import AsightROle from './components/AsightROle.vue'
import { getEmployeeListAPI, delEEAPI } from '@/api'
import EmployeeEnum from '@/api/constant/employees'
import { dayForm } from '@/utils/formateDate'
export default {
  components: {
    AddEE,
    AsightROle
  },
  data() {
    return {
      userId: null,
      roleDialogShow: false,
      showCodeDialog: false,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      list: [],
      loading: false,
      addPopShow: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    qrCode(url) {
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeListAPI(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    onchangPage(newPage) {
      // this.loading = true
      this.page.page = newPage
      this.getEmployeeList()
      // this.loading = false
    },
    colFormate(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(el => el.id === cellValue)
      return obj ? obj.value : '未知'
    },

    // 删除员工
    async delEE(id) {
      try {
        await this.$confirm('确定删除吗？')
        await delEEAPI(id)
        const index = this.list.findIndex(el => el.id === id)
        console.log(index)
        this.list.splice(index, 1)
      } catch (err) {
        console.log(err.message)
      }
    },

    // 控制弹层显示
    addEE() {
      this.addPopShow = true
    },
    onImport() {
      this.$router.push('./exportExcel')
    },

    async onExport() {
      const { rows } = await getEmployeeListAPI({ page: 1, size: this.page.total })
      const header = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = rows.map(el => {
        return Object.keys(header).map(key => {
          return header[key] === 'timeOfEntry' || header[key] === 'correctionTime' ? dayForm(el[header[key]]) : el[header[key]]
        })
      })
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(header), // 表头 必填
          data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader,
          merges
        })
      })
    },

    // 角色弹出
    async roleBtn(id) {
      this.userId = id
      await this.$refs.roleDialog.getRoleInfo(id)
      this.roleDialogShow = true
    }
  }
}
</script>

<style>

</style>
